//
//  localViewController.m
//  BabyBedtimeStory
//
//  Created by qianfeng on 15-7-1.
//  Copyright (c) 2015年 张鹏毅. All rights reserved.
//

#import "localViewController.h"
#import "DetailViewController.h"
#define kScreenSize [UIScreen mainScreen].bounds.size
@interface localViewController ()<AVAudioPlayerDelegate>
{
    UISlider *_slider;
    UILabel *_label;
    UILabel *_currentTimeLabel;
}
@property (nonatomic) BOOL isYes;
@end

@implementation localViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    self.isYes = NO;
    [self creatLeftItem];
    [self creatPlaying];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(defaultClick:) name:kFabcdefg object:nil];
    [self creatTime];
}

-(void)defaultClick:(NSNotification *)tyf{
    [localPlayer pause];
}

+(AVAudioPlayer *)sharedSingleton{
    @synchronized (self){
        if (!localPlayer) {
            localPlayer = nil;
            localPlayer = [[self alloc] init];
        }
    }
    return localPlayer;
}

-(void)creatLeftItem{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(0, 0, 30, 30);
    [button setImage:[[UIImage imageNamed:@"ic_nac_back_down"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    button.tag = 501;
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = item;
}

-(void)creatPlaying{
    NSArray *arr = @[@"ic_start"];
    for (NSInteger i = 0; i < arr.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(kScreenSize.width/2-40, kScreenSize.height-250+50*i, 80, 80);
        [button setImage:[[UIImage imageNamed:arr[i]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        button.tag = 101+i;
        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
    }
    NSString *paths = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString *str = [paths stringByAppendingPathComponent:self.str];
    localPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:str] error:nil];
    localPlayer.delegate = self;
    [localPlayer prepareToPlay];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [NSThread sleepForTimeInterval:1];
        dispatch_async(dispatch_get_main_queue(), ^{
            UIButton *button = (UIButton *)[self.view viewWithTag:101];
            [button setImage:[[UIImage imageNamed:@"ic_suspended"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            self.isYes = YES;
            [self justPlay];
        });
    });
    [self creatSlider];
}
- (void)btnClick:(UIButton *)button {
    switch (button.tag) {
        case 101://播放
        {
            if (!self.isYes) {
                 [button setImage:[[UIImage imageNamed:@"ic_suspended"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
                self.isYes = YES;
                 [self justPlay];
            }else{
                [button setImage:[[UIImage imageNamed:@"ic_start"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
                [localPlayer pause];
                self.isYes = NO;
            }
        }
            break;
            
        default:
            break;
    }
}

- (void)creatSlider {
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 75, kScreenSize.width-20, kScreenSize.height-65-290)];
    imageView.image = [UIImage imageNamed:@"background"];
    [self.view addSubview:imageView];
    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(uptimerClick:) userInfo:nil repeats:YES];
    _slider = [[UISlider alloc] initWithFrame:CGRectMake(0, kScreenSize.height-150, self.view.bounds.size.width, 30)];
    _slider.minimumValue = 0.0;
    _slider.maximumValue = 1.0;
    _slider.value = 0;

    [_slider addTarget:self action:@selector(sliderClick:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_slider];
    
    _label = [[UILabel alloc] initWithFrame:CGRectMake(0, 300, 320, 50)];
    _label.numberOfLines = 0;
    _label.textColor = [UIColor redColor];
    _label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_label];
    
}

- (void)sliderClick:(UISlider *)slider {
    localPlayer.currentTime = localPlayer.duration*slider.value;
}
- (void)uptimerClick:(NSTimer *)timer {
    _slider.value = localPlayer.currentTime/localPlayer.duration;
}
#pragma mark - AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)btnClick{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)creatTime{
    UILabel *totalTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(kScreenSize.width-69, kScreenSize.height-130, 80, 50)];
    totalTimeLabel.text = [self TimeChange:(int)localPlayer.duration];
    totalTimeLabel.font = [UIFont fontWithName:@"Didot" size:14];
    [self.view addSubview:totalTimeLabel];
    _currentTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(9, kScreenSize.height-130, 80, 50)];
    _currentTimeLabel.text = @"00:00:00";
    _currentTimeLabel.font = [UIFont fontWithName:@"Didot" size:14];
    _currentTimeLabel.numberOfLines = 0;
    [self.view addSubview:_currentTimeLabel];
}

-(NSString *)TimeChange:(int)time{
    int h = 0;
    int m = 0;
    int s = 0;
    if (time/60>=1) {
        if (time/3600>=1) {
            h = time%3600;
            time = time - 3600*h;
        }
        m = time/60;
        time = time - 60*m;
    }
    s = time;
    return [NSString stringWithFormat:@"%02d:%02d:%02d",h,m,s];
}

-(void)justPlay{
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [localPlayer play];
}

@end
